<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">参数管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 商品选择分类 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类 ： </span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="Catelist"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="用户管理" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 添加参数数据 -->
          <el-table :data="manyTabData" border stripe="">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- for 添加tab标签 -->
                <el-tag
                  closable
                  v-for="(item, ind) in scope.row.attr_vals"
                  :key="ind"
                  @close="handleClose(ind,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tab标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEidtDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-edit"
                  @click="reomveParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="配置管理" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 添加属性面板 -->
          <el-table :data="onlyTabData" border stripe="">
               <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- for 添加tab标签 -->
                <el-tag
                  closable
                  v-for="(item, ind) in scope.row.attr_vals"
                  :key="ind"
                  @close="handleClose(ind,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加tab标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEidtDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-edit"
                  @click="reomveParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性的对话框 -->
    <el-dialog
      :title="'添加' + titleTxt"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item :label="titleTxt" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数对话框 -->
    <el-dialog
      :title="'修改' + titleTxt"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="80px"
        :rules="addFormRules"
      >
        <el-form-item :label="titleTxt" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品分类数据
      Catelist: [],
      //级联选择器配置
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        childeren: "children",
        expandTrigger: "hover",
      },
      //级联选择器绑定的数组
      selectedCateKeys: [],
      //tab页签选中的名称
      activeName: "many",
      //动态参数和静态属性的数据
      manyTabData: [],
      onlyTabData: [],
      //控制添加参数和属性的对话框
      addDialogVisible: false,
      //添加分类 属性 绑定的数据
      addForm: {
        attr_name: "",
      },
      //数据校验
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      //编辑的对话框
      editDialogVisible: false,
      //编辑参数的数据
      editForm: {},
  
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取到商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      //   console.log(res);
      this.Catelist = res.data;
    },
    //级联选择器的事件
    handleChange() {
      this.getParamsData();
    },
    //tab页签点击事件
    handleTabClick() {
      this.getParamsData();
    },
    //获取参数列表数据
    async getParamsData() {
  
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = [];
        this.manyTabData = []
        this.onlyTabData = []
        return;
      }
      //获取到选中的三级分类数据
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // console.log(res.data);
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //控制输入框显示与隐藏
        item.inputVisible = false
        // 输入框绑定的数据内容
        item.inputValue = ""
      });

      if (this.activeName === "many") {
        this.manyTabData = res.data;
      } else {
        this.onlyTabData = res.data;
      }
    },
    //监听对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //添加分类的确认按钮
    addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        );
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        //重新渲染
        this.getParamsData();
        this.addDialogVisible = false;
        //  console.log(res.data);
      });
    },
    //编辑参数
    async showEidtDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;
      console.log(res.data);
      this.editDialogVisible = true;
    },
    //关闭编辑对话框的事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //编辑对话框的确认按钮
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        //重新渲染
        this.getParamsData();
        this.editDialogVisible = false;
      });
    },
    //删除参数
    async reomveParams(attr_id) {
      const confirmRult = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmRult !== "confirm") return this.$message.info("已取消");
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      //重新渲染数据
      this.getParamsData();
    },
    //添加tab标签的inp事件
    handleInputConfirm (row) {
      //判断输入的内容是否合法
      if(row.inputValue.trim().length === 0) {
          row.inputValue =''
      row.inputVisible = false
      return 
      }
      row.attr_vals.push(row.inputValue)
          row.inputValue =''
      row.inputVisible = false

      this.saveAttVals(row) 
      
    },
    //添加tab 标签的按钮点击事件
    showInput(row) {
      row.inputVisible = true
      //让输入框自动获取到焦点
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    //发起修改数据的参数
   async saveAttVals(row) {
 const { data:res} =await  this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name : row.attr_name,
        attr_sel : this.activeName,
        attr_vals : row.attr_vals.join(' ')
      })
        if(res.meta.status !== 200) return this.$message.error('添加失败')
        this.$message.success(res.meta.msg)
    },
    //删除tab标签
    handleClose(ind,row) {
      row.attr_vals.splice(ind,1)
    this.saveAttVals(row) 
    }
  },
  computed: {
    //判断是否选中的是三级分类禁用按钮
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 获取到3级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2];
      }
      return null;
    },
    //动态控制对话框标体
    titleTxt() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag{
  width: 100px;
}
</style>>
